package com.renbang.test.an.fanxing;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class WebxmlUtils {

	public static void main(String[] args) throws Exception {
		System.out.println(getWeather("上海"));
	}

	public static String getWeather(String city) throws Exception {
		URL url = new URL(
				"http://ws.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather?theUserID=&theCityCode="+city);
		URLConnection uc = url.openConnection();
		InputStream br = uc.getInputStream();
		Document doc;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(true);
		DocumentBuilder db = dbf.newDocumentBuilder();
		doc = db.parse(br);// 得到doc文档
		NodeList nl = doc.getElementsByTagName("string");
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < nl.getLength(); i++) {
			Node n = nl.item(i);
			String weather = n.getFirstChild().getNodeValue();
			sb.append(weather + "\n");
		}
		return sb.toString();
	}
}
